package br.edu.intec.agenda.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import br.edu.intec.agenda.exception.DAOException;


public abstract class GenericDao {
	
	private Connection conn;
	private PreparedStatement pstm;

	protected void inserir(String sql, Object...parametros) throws DAOException{
		
		try {
			
			conn = ConnectionFactory.getConnection();
			pstm = conn.prepareStatement(sql);
			
			for (int i = 0; i < parametros.length; i++) {
				pstm.setObject(i+1, parametros[i]);
			}
			
			pstm.execute();
			
		} catch (SQLException e) {
			throw new DAOException("Falha ao inserir, tente novamente!");
		} catch (DAOException e) {
			throw new DAOException(e.getMessage());
		} finally {
			ConnectionFactory.closeConnection(conn, pstm);
		}
	}
	
	protected void atualizar(String sql, Integer id, Object...parametros) throws DAOException{
		try {
			
			conn = ConnectionFactory.getConnection();
			pstm = conn.prepareStatement(sql);
			
			for (int i = 0; i < parametros.length; i++) {
				pstm.setObject(i+1, parametros[i]);
			}
			
			pstm.setInt(parametros.length + 1, id);
			
			pstm.execute();
			
		} catch (SQLException e) {
			throw new DAOException("Erro ao atualizar, tente novamente!");
		} catch (DAOException e) {
			throw new DAOException(e.getMessage());
		} finally {
			ConnectionFactory.closeConnection(conn, pstm);
		}
	}
	
	protected void excluir(String sql, Object...parametros) throws DAOException{
		
		try {
			
			conn = ConnectionFactory.getConnection();
			pstm = conn.prepareStatement(sql);
			
			for (int i = 0; i < parametros.length; i++) {
				pstm.setObject(i+1, parametros[i]);
			}
			
			pstm.execute();
			
		} catch (SQLException e) {
			throw new DAOException("Falha ao inserir, tente novamente!");
		} catch (DAOException e) {
			throw new DAOException(e.getMessage());
		} finally {
			ConnectionFactory.closeConnection(conn, pstm);
		}
	}	
	
}
